# @file    : completions_test
# @time    : 2025/4/2
# @author  : yongpeng.yao
# @desc    :
import json
import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(api_key=os.getenv('DEEPSEEK_API_KEY'), base_url="https://api.deepseek.com")


def get_flower_inventory(city):
    """获取指定城市的鲜花库存"""
    if "北京" in city:
        return json.dumps({"city": "北京", "inventory": "玫瑰: 100, 郁金香: 150"})
    elif "上海" in city:
        return json.dumps({"city": "上海", "inventory": "百合: 80, 康乃馨: 120"})
    elif "深圳" in city:
        return json.dumps({"city": "深圳", "inventory": "向日葵: 200, 玉兰: 90"})
    else:
        return json.dumps({"city": city, "inventory": "未知"})


tools = [
    {
        'type': 'function',
        'function': {
            'name': 'get_flower_inventory',
            'description': '获取鲜花库存',
            'parameters': {
                'type': 'object',
                'properties': {
                    'city': {
                        'type': 'string',
                        'description': '城市名称，列如 北京、上海、深圳',
                    },
                },
                'required': ['city'],
            },
        },
    }
]

messages = [
    {'role': 'user',
     'content': '北京、上海和深圳的鲜花库存是多少？'}
]

first_response = client.chat.completions.create(
    model='deepseek-chat',
    messages=messages,
    tools=tools,
    tool_choice='auto'
)

print(first_response)

response_message = first_response.choices[0].message

tool_calls = response_message.tool_calls
if tool_calls:
    messages.append(response_message)
    for tool_call in tool_calls:
        function_call = tool_call.function
        function_name = function_call.name
        print(f'正在调用函数：{function_name}')
        function_arguments = json.loads(function_call.arguments)
        print(f'{function_name}函数参数：{function_arguments}')
        function_response = eval(f'{function_name}(**{function_arguments})')
        print(f'{function_name}函数返回值：{function_response}')
        messages.append({
            'role': 'tool',
            'tool_call_id': tool_call.id,
            'name': function_name,
            'content': function_response,
        })
print(messages)

second_response = client.chat.completions.create(
    model='deepseek-chat',
    messages=messages
)

final_response = second_response.choices[0].message
print(f'最终响应：\n{final_response.content}')
